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/capsicum.h>
116 #include <sys/fcntl.h>
117 #include <sys/limits.h>
118 #include <sys/lock.h>
120 #include <sys/malloc.h>
121 #include <sys/mbuf.h>
122 #include <sys/mutex.h>
123 #include <sys/domain.h>
124 #include <sys/file.h> /* for struct knote */
125 #include <sys/hhook.h>
126 #include <sys/kernel.h>
127 #include <sys/khelp.h>
128 #include <sys/ktls.h>
129 #include <sys/event.h>
130 #include <sys/eventhandler.h>
131 #include <sys/poll.h>
132 #include <sys/proc.h>
133 #include <sys/protosw.h>
134 #include <sys/sbuf.h>
135 #include <sys/socket.h>
136 #include <sys/socketvar.h>
137 #include <sys/resourcevar.h>
138 #include <net/route.h>
139 #include <sys/signalvar.h>
140 #include <sys/stat.h>
142 #include <sys/sysctl.h>
143 #include <sys/taskqueue.h>
146 #include <sys/unpcb.h>
147 #include <sys/jail.h>
148 #include <sys/syslog.h>
149 #include <netinet/in.h>
150 #include <netinet/in_pcb.h>
151 #include <netinet/tcp.h>
153 #include <net/vnet.h>
155 #include <security/mac/mac_framework.h>
159 #ifdef COMPAT_FREEBSD32
160 #include <sys/mount.h>
161 #include <sys/sysent.h>
162 #include <compat/freebsd32/freebsd32.h>
165 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
167 static void so_rdknl_lock(void *);
168 static void so_rdknl_unlock(void *);
169 static void so_rdknl_assert_lock(void *, int);
170 static void so_wrknl_lock(void *);
171 static void so_wrknl_unlock(void *);
172 static void so_wrknl_assert_lock(void *, int);
174 static void filt_sordetach(struct knote *kn);
175 static int filt_soread(struct knote *kn, long hint);
176 static void filt_sowdetach(struct knote *kn);
177 static int filt_sowrite(struct knote *kn, long hint);
178 static int filt_soempty(struct knote *kn, long hint);
179 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
180 fo_kqfilter_t soo_kqfilter;
182 static struct filterops soread_filtops = {
184 .f_detach = filt_sordetach,
185 .f_event = filt_soread,
187 static struct filterops sowrite_filtops = {
189 .f_detach = filt_sowdetach,
190 .f_event = filt_sowrite,
192 static struct filterops soempty_filtops = {
194 .f_detach = filt_sowdetach,
195 .f_event = filt_soempty,
198 so_gen_t so_gencnt; /* generation count for sockets */
200 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
201 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
203 #define VNET_SO_ASSERT(so) \
204 VNET_ASSERT(curvnet != NULL, \
205 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
207 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
208 #define V_socket_hhh VNET(socket_hhh)
211 * Limit on the number of connections in the listen queue waiting
213 * NB: The original sysctl somaxconn is still available but hidden
214 * to prevent confusion about the actual purpose of this number.
216 static u_int somaxconn = SOMAXCONN;
219 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
225 error = sysctl_handle_int(oidp, &val, 0, req);
226 if (error || !req->newptr )
230 * The purpose of the UINT_MAX / 3 limit, is so that the formula
232 * below, will not overflow.
235 if (val < 1 || val > UINT_MAX / 3)
241 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue,
242 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(int),
243 sysctl_somaxconn, "I",
244 "Maximum listen socket pending connection accept queue size");
245 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
246 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP | CTLFLAG_MPSAFE, 0,
247 sizeof(int), sysctl_somaxconn, "I",
248 "Maximum listen socket pending connection accept queue size (compat)");
250 static int numopensockets;
251 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
252 &numopensockets, 0, "Number of open sockets");
255 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
258 static struct mtx so_global_mtx;
259 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
262 * General IPC sysctl name space, used by sockets and a variety of other IPC
265 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
269 * Initialize the socket subsystem and set up the socket
272 static uma_zone_t socket_zone;
276 socket_zone_change(void *tag)
279 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
283 socket_hhook_register(int subtype)
286 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
287 &V_socket_hhh[subtype],
288 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
289 printf("%s: WARNING: unable to register hook\n", __func__);
293 socket_hhook_deregister(int subtype)
296 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
297 printf("%s: WARNING: unable to deregister hook\n", __func__);
301 socket_init(void *tag)
304 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
305 NULL, NULL, UMA_ALIGN_PTR, 0);
306 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
307 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
308 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
309 EVENTHANDLER_PRI_FIRST);
311 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
314 socket_vnet_init(const void *unused __unused)
318 /* We expect a contiguous range */
319 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
320 socket_hhook_register(i);
322 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
323 socket_vnet_init, NULL);
326 socket_vnet_uninit(const void *unused __unused)
330 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
331 socket_hhook_deregister(i);
333 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
334 socket_vnet_uninit, NULL);
337 * Initialise maxsockets. This SYSINIT must be run after
341 init_maxsockets(void *ignored)
344 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
345 maxsockets = imax(maxsockets, maxfiles);
347 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
350 * Sysctl to get and set the maximum global sockets limit. Notify protocols
351 * of the change so that they can update their dependent limits as required.
354 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
356 int error, newmaxsockets;
358 newmaxsockets = maxsockets;
359 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
360 if (error == 0 && req->newptr && newmaxsockets != maxsockets) {
361 if (newmaxsockets > maxsockets &&
362 newmaxsockets <= maxfiles) {
363 maxsockets = newmaxsockets;
364 EVENTHANDLER_INVOKE(maxsockets_change);
370 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets,
371 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, &maxsockets, 0,
372 sysctl_maxsockets, "IU",
373 "Maximum number of sockets available");
376 * Socket operation routines. These routines are called by the routines in
377 * sys_socket.c or from a system process, and implement the semantics of
378 * socket operations by switching out to the protocol specific routines.
382 * Get a socket structure from our zone, and initialize it. Note that it
383 * would probably be better to allocate socket and PCB at the same time, but
384 * I'm not convinced that all the protocols can be easily modified to do
387 * soalloc() returns a socket with a ref count of 0.
389 static struct socket *
390 soalloc(struct vnet *vnet)
394 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
398 if (mac_socket_init(so, M_NOWAIT) != 0) {
399 uma_zfree(socket_zone, so);
403 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
404 uma_zfree(socket_zone, so);
409 * The socket locking protocol allows to lock 2 sockets at a time,
410 * however, the first one must be a listening socket. WITNESS lacks
411 * a feature to change class of an existing lock, so we use DUPOK.
413 mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK);
414 mtx_init(&so->so_snd_mtx, "so_snd", NULL, MTX_DEF);
415 mtx_init(&so->so_rcv_mtx, "so_rcv", NULL, MTX_DEF);
416 so->so_rcv.sb_sel = &so->so_rdsel;
417 so->so_snd.sb_sel = &so->so_wrsel;
418 sx_init(&so->so_snd_sx, "so_snd_sx");
419 sx_init(&so->so_rcv_sx, "so_rcv_sx");
420 TAILQ_INIT(&so->so_snd.sb_aiojobq);
421 TAILQ_INIT(&so->so_rcv.sb_aiojobq);
422 TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
423 TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
425 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
426 __func__, __LINE__, so));
429 /* We shouldn't need the so_global_mtx */
430 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
431 /* Do we need more comprehensive error returns? */
432 uma_zfree(socket_zone, so);
435 mtx_lock(&so_global_mtx);
436 so->so_gencnt = ++so_gencnt;
439 vnet->vnet_sockcnt++;
441 mtx_unlock(&so_global_mtx);
447 * Free the storage associated with a socket at the socket layer, tear down
448 * locks, labels, etc. All protocol state is assumed already to have been
449 * torn down (and possibly never set up) by the caller.
452 sodealloc(struct socket *so)
455 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
456 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
458 mtx_lock(&so_global_mtx);
459 so->so_gencnt = ++so_gencnt;
460 --numopensockets; /* Could be below, but faster here. */
462 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
463 __func__, __LINE__, so));
464 so->so_vnet->vnet_sockcnt--;
466 mtx_unlock(&so_global_mtx);
468 mac_socket_destroy(so);
470 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
472 khelp_destroy_osd(&so->osd);
473 if (SOLISTENING(so)) {
474 if (so->sol_accept_filter != NULL)
475 accept_filt_setopt(so, NULL);
477 if (so->so_rcv.sb_hiwat)
478 (void)chgsbsize(so->so_cred->cr_uidinfo,
479 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
480 if (so->so_snd.sb_hiwat)
481 (void)chgsbsize(so->so_cred->cr_uidinfo,
482 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
483 sx_destroy(&so->so_snd_sx);
484 sx_destroy(&so->so_rcv_sx);
485 mtx_destroy(&so->so_snd_mtx);
486 mtx_destroy(&so->so_rcv_mtx);
489 mtx_destroy(&so->so_lock);
490 uma_zfree(socket_zone, so);
494 * socreate returns a socket with a ref count of 1 and a file descriptor
495 * reference. The socket should be closed with soclose().
498 socreate(int dom, struct socket **aso, int type, int proto,
499 struct ucred *cred, struct thread *td)
506 * XXX: divert(4) historically abused PF_INET. Keep this compatibility
507 * shim until all applications have been updated.
509 if (__predict_false(dom == PF_INET && type == SOCK_RAW &&
510 proto == IPPROTO_DIVERT)) {
512 printf("%s uses obsolete way to create divert(4) socket\n",
513 td->td_proc->p_comm);
516 prp = pffindproto(dom, type, proto);
518 /* No support for domain. */
519 if (pffinddomain(dom) == NULL)
520 return (EAFNOSUPPORT);
521 /* No support for socket type. */
522 if (proto == 0 && type != 0)
524 return (EPROTONOSUPPORT);
527 MPASS(prp->pr_attach);
529 if (IN_CAPABILITY_MODE(td) && (prp->pr_flags & PR_CAPATTACH) == 0)
532 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
533 return (EPROTONOSUPPORT);
535 so = soalloc(CRED_TO_VNET(cred));
540 so->so_cred = crhold(cred);
541 if ((prp->pr_domain->dom_family == PF_INET) ||
542 (prp->pr_domain->dom_family == PF_INET6) ||
543 (prp->pr_domain->dom_family == PF_ROUTE))
544 so->so_fibnum = td->td_proc->p_fibnum;
549 mac_socket_create(cred, so);
551 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
552 so_rdknl_assert_lock);
553 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
554 so_wrknl_assert_lock);
555 if ((prp->pr_flags & PR_SOCKBUF) == 0) {
556 so->so_snd.sb_mtx = &so->so_snd_mtx;
557 so->so_rcv.sb_mtx = &so->so_rcv_mtx;
560 * Auto-sizing of socket buffers is managed by the protocols and
561 * the appropriate flags must be set in the pru_attach function.
563 CURVNET_SET(so->so_vnet);
564 error = prp->pr_attach(so, proto, td);
576 static int regression_sonewconn_earlytest = 1;
577 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
578 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
581 static struct timeval overinterval = { 60, 0 };
582 SYSCTL_TIMEVAL_SEC(_kern_ipc, OID_AUTO, sooverinterval, CTLFLAG_RW,
584 "Delay in seconds between warnings for listen socket overflows");
587 * When an attempt at a new connection is noted on a socket which supports
588 * accept(2), the protocol has two options:
589 * 1) Call legacy sonewconn() function, which would call protocol attach
590 * method, same as used for socket(2).
591 * 2) Call solisten_clone(), do attach that is specific to a cloned connection,
592 * and then call solisten_enqueue().
594 * Note: the ref count on the socket is 0 on return.
597 solisten_clone(struct socket *head)
603 const char localprefix[] = "local:";
604 char descrbuf[SUNPATHLEN + sizeof(localprefix)];
606 char addrbuf[INET6_ADDRSTRLEN];
608 char addrbuf[INET_ADDRSTRLEN];
613 over = (head->sol_qlen > 3 * head->sol_qlimit / 2);
615 if (regression_sonewconn_earlytest && over) {
619 head->sol_overcount++;
620 dolog = !!ratecheck(&head->sol_lastover, &overinterval);
623 * If we're going to log, copy the overflow count and queue
624 * length from the listen socket before dropping the lock.
625 * Also, reset the overflow count.
628 overcount = head->sol_overcount;
629 head->sol_overcount = 0;
630 qlen = head->sol_qlen;
632 SOLISTEN_UNLOCK(head);
636 * Try to print something descriptive about the
637 * socket for the error message.
639 sbuf_new(&descrsb, descrbuf, sizeof(descrbuf),
641 switch (head->so_proto->pr_domain->dom_family) {
642 #if defined(INET) || defined(INET6)
648 if (head->so_proto->pr_domain->dom_family ==
650 (sotoinpcb(head)->inp_inc.inc_flags &
653 &sotoinpcb(head)->inp_inc.inc6_laddr);
654 sbuf_printf(&descrsb, "[%s]", addrbuf);
660 sotoinpcb(head)->inp_inc.inc_laddr,
662 sbuf_cat(&descrsb, addrbuf);
665 sbuf_printf(&descrsb, ":%hu (proto %u)",
666 ntohs(sotoinpcb(head)->inp_inc.inc_lport),
667 head->so_proto->pr_protocol);
669 #endif /* INET || INET6 */
671 sbuf_cat(&descrsb, localprefix);
672 if (sotounpcb(head)->unp_addr != NULL)
674 sotounpcb(head)->unp_addr->sun_len -
675 offsetof(struct sockaddr_un,
681 sotounpcb(head)->unp_addr->sun_path,
684 sbuf_cat(&descrsb, "(unknown)");
689 * If we can't print something more specific, at least
690 * print the domain name.
692 if (sbuf_finish(&descrsb) != 0 ||
693 sbuf_len(&descrsb) <= 0) {
694 sbuf_clear(&descrsb);
696 head->so_proto->pr_domain->dom_name ?:
698 sbuf_finish(&descrsb);
700 KASSERT(sbuf_len(&descrsb) > 0,
701 ("%s: sbuf creation failed", __func__));
703 * Preserve the historic listen queue overflow log
704 * message, that starts with "sonewconn:". It has
705 * been known to sysadmins for years and also test
706 * sys/kern/sonewconn_overflow checks for it.
708 if (head->so_cred == 0) {
709 log(LOG_DEBUG, "sonewconn: pcb %p (%s): "
710 "Listen queue overflow: %i already in "
711 "queue awaiting acceptance (%d "
712 "occurrences)\n", head->so_pcb,
716 log(LOG_DEBUG, "sonewconn: pcb %p (%s): "
717 "Listen queue overflow: "
718 "%i already in queue awaiting acceptance "
719 "(%d occurrences), euid %d, rgid %d, jail %s\n",
720 head->so_pcb, sbuf_data(&descrsb), qlen,
721 overcount, head->so_cred->cr_uid,
722 head->so_cred->cr_rgid,
723 head->so_cred->cr_prison ?
724 head->so_cred->cr_prison->pr_name :
727 sbuf_delete(&descrsb);
734 SOLISTEN_UNLOCK(head);
735 VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL",
737 so = soalloc(head->so_vnet);
739 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
740 "limit reached or out of memory\n",
741 __func__, head->so_pcb);
744 so->so_listen = head;
745 so->so_type = head->so_type;
746 so->so_options = head->so_options & ~SO_ACCEPTCONN;
747 so->so_linger = head->so_linger;
748 so->so_state = head->so_state;
749 so->so_fibnum = head->so_fibnum;
750 so->so_proto = head->so_proto;
751 so->so_cred = crhold(head->so_cred);
753 mac_socket_newconn(head, so);
755 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
756 so_rdknl_assert_lock);
757 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
758 so_wrknl_assert_lock);
759 VNET_SO_ASSERT(head);
760 if (soreserve(so, head->sol_sbsnd_hiwat, head->sol_sbrcv_hiwat)) {
762 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
763 __func__, head->so_pcb);
766 so->so_rcv.sb_lowat = head->sol_sbrcv_lowat;
767 so->so_snd.sb_lowat = head->sol_sbsnd_lowat;
768 so->so_rcv.sb_timeo = head->sol_sbrcv_timeo;
769 so->so_snd.sb_timeo = head->sol_sbsnd_timeo;
770 so->so_rcv.sb_flags = head->sol_sbrcv_flags & SB_AUTOSIZE;
771 so->so_snd.sb_flags = head->sol_sbsnd_flags & SB_AUTOSIZE;
772 if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) {
773 so->so_snd.sb_mtx = &so->so_snd_mtx;
774 so->so_rcv.sb_mtx = &so->so_rcv_mtx;
780 /* Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED. */
782 sonewconn(struct socket *head, int connstatus)
786 if ((so = solisten_clone(head)) == NULL)
789 if (so->so_proto->pr_attach(so, 0, NULL) != 0) {
791 log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n",
792 __func__, head->so_pcb);
796 (void)solisten_enqueue(so, connstatus);
802 * Enqueue socket cloned by solisten_clone() to the listen queue of the
803 * listener it has been cloned from.
805 * Return 'true' if socket landed on complete queue, otherwise 'false'.
808 solisten_enqueue(struct socket *so, int connstatus)
810 struct socket *head = so->so_listen;
812 MPASS(refcount_load(&so->so_count) == 0);
813 refcount_init(&so->so_count, 1);
816 if (head->sol_accept_filter != NULL)
818 so->so_state |= connstatus;
819 soref(head); /* A socket on (in)complete queue refs head. */
821 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
822 so->so_qstate = SQ_COMP;
824 solisten_wakeup(head); /* unlocks */
828 * Keep removing sockets from the head until there's room for
829 * us to insert on the tail. In pre-locking revisions, this
830 * was a simple if(), but as we could be racing with other
831 * threads and soabort() requires dropping locks, we must
832 * loop waiting for the condition to be true.
834 while (head->sol_incqlen > head->sol_qlimit) {
837 sp = TAILQ_FIRST(&head->sol_incomp);
838 TAILQ_REMOVE(&head->sol_incomp, sp, so_list);
841 sp->so_qstate = SQ_NONE;
842 sp->so_listen = NULL;
844 sorele_locked(head); /* does SOLISTEN_UNLOCK, head stays */
848 TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list);
849 so->so_qstate = SQ_INCOMP;
851 SOLISTEN_UNLOCK(head);
856 #if defined(SCTP) || defined(SCTP_SUPPORT)
858 * Socket part of sctp_peeloff(). Detach a new socket from an
859 * association. The new socket is returned with a reference.
861 * XXXGL: reduce copy-paste with solisten_clone().
864 sopeeloff(struct socket *head)
868 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
869 __func__, __LINE__, head));
870 so = soalloc(head->so_vnet);
872 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
873 "limit reached or out of memory\n",
874 __func__, head->so_pcb);
877 so->so_type = head->so_type;
878 so->so_options = head->so_options;
879 so->so_linger = head->so_linger;
880 so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED;
881 so->so_fibnum = head->so_fibnum;
882 so->so_proto = head->so_proto;
883 so->so_cred = crhold(head->so_cred);
885 mac_socket_newconn(head, so);
887 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
888 so_rdknl_assert_lock);
889 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
890 so_wrknl_assert_lock);
891 VNET_SO_ASSERT(head);
892 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
894 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
895 __func__, head->so_pcb);
898 if ((*so->so_proto->pr_attach)(so, 0, NULL)) {
900 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
901 __func__, head->so_pcb);
904 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
905 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
906 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
907 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
908 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
909 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
918 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
922 CURVNET_SET(so->so_vnet);
923 error = so->so_proto->pr_bind(so, nam, td);
929 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
933 CURVNET_SET(so->so_vnet);
934 error = so->so_proto->pr_bindat(fd, so, nam, td);
940 * solisten() transitions a socket from a non-listening state to a listening
941 * state, but can also be used to update the listen queue depth on an
942 * existing listen socket. The protocol will call back into the sockets
943 * layer using solisten_proto_check() and solisten_proto() to check and set
944 * socket-layer listen state. Call backs are used so that the protocol can
945 * acquire both protocol and socket layer locks in whatever order is required
948 * Protocol implementors are advised to hold the socket lock across the
949 * socket-layer test and set to avoid races at the socket layer.
952 solisten(struct socket *so, int backlog, struct thread *td)
956 CURVNET_SET(so->so_vnet);
957 error = so->so_proto->pr_listen(so, backlog, td);
963 * Prepare for a call to solisten_proto(). Acquire all socket buffer locks in
964 * order to interlock with socket I/O.
967 solisten_proto_check(struct socket *so)
969 SOCK_LOCK_ASSERT(so);
971 if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
972 SS_ISDISCONNECTING)) != 0)
976 * Sleeping is not permitted here, so simply fail if userspace is
977 * attempting to transmit or receive on the socket. This kind of
978 * transient failure is not ideal, but it should occur only if userspace
979 * is misusing the socket interfaces.
981 if (!sx_try_xlock(&so->so_snd_sx))
983 if (!sx_try_xlock(&so->so_rcv_sx)) {
984 sx_xunlock(&so->so_snd_sx);
987 mtx_lock(&so->so_snd_mtx);
988 mtx_lock(&so->so_rcv_mtx);
990 /* Interlock with soo_aio_queue(). */
991 if (!SOLISTENING(so) &&
992 ((so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 ||
993 (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0)) {
994 solisten_proto_abort(so);
1001 * Undo the setup done by solisten_proto_check().
1004 solisten_proto_abort(struct socket *so)
1006 mtx_unlock(&so->so_snd_mtx);
1007 mtx_unlock(&so->so_rcv_mtx);
1008 sx_xunlock(&so->so_snd_sx);
1009 sx_xunlock(&so->so_rcv_sx);
1013 solisten_proto(struct socket *so, int backlog)
1015 int sbrcv_lowat, sbsnd_lowat;
1016 u_int sbrcv_hiwat, sbsnd_hiwat;
1017 short sbrcv_flags, sbsnd_flags;
1018 sbintime_t sbrcv_timeo, sbsnd_timeo;
1020 SOCK_LOCK_ASSERT(so);
1021 KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1022 SS_ISDISCONNECTING)) == 0,
1023 ("%s: bad socket state %p", __func__, so));
1025 if (SOLISTENING(so))
1029 * Change this socket to listening state.
1031 sbrcv_lowat = so->so_rcv.sb_lowat;
1032 sbsnd_lowat = so->so_snd.sb_lowat;
1033 sbrcv_hiwat = so->so_rcv.sb_hiwat;
1034 sbsnd_hiwat = so->so_snd.sb_hiwat;
1035 sbrcv_flags = so->so_rcv.sb_flags;
1036 sbsnd_flags = so->so_snd.sb_flags;
1037 sbrcv_timeo = so->so_rcv.sb_timeo;
1038 sbsnd_timeo = so->so_snd.sb_timeo;
1040 sbdestroy(so, SO_SND);
1041 sbdestroy(so, SO_RCV);
1045 sizeof(struct socket) - offsetof(struct socket, so_rcv));
1048 so->sol_sbrcv_lowat = sbrcv_lowat;
1049 so->sol_sbsnd_lowat = sbsnd_lowat;
1050 so->sol_sbrcv_hiwat = sbrcv_hiwat;
1051 so->sol_sbsnd_hiwat = sbsnd_hiwat;
1052 so->sol_sbrcv_flags = sbrcv_flags;
1053 so->sol_sbsnd_flags = sbsnd_flags;
1054 so->sol_sbrcv_timeo = sbrcv_timeo;
1055 so->sol_sbsnd_timeo = sbsnd_timeo;
1057 so->sol_qlen = so->sol_incqlen = 0;
1058 TAILQ_INIT(&so->sol_incomp);
1059 TAILQ_INIT(&so->sol_comp);
1061 so->sol_accept_filter = NULL;
1062 so->sol_accept_filter_arg = NULL;
1063 so->sol_accept_filter_str = NULL;
1065 so->sol_upcall = NULL;
1066 so->sol_upcallarg = NULL;
1068 so->so_options |= SO_ACCEPTCONN;
1071 if (backlog < 0 || backlog > somaxconn)
1072 backlog = somaxconn;
1073 so->sol_qlimit = backlog;
1075 mtx_unlock(&so->so_snd_mtx);
1076 mtx_unlock(&so->so_rcv_mtx);
1077 sx_xunlock(&so->so_snd_sx);
1078 sx_xunlock(&so->so_rcv_sx);
1082 * Wakeup listeners/subsystems once we have a complete connection.
1083 * Enters with lock, returns unlocked.
1086 solisten_wakeup(struct socket *sol)
1089 if (sol->sol_upcall != NULL)
1090 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
1092 selwakeuppri(&sol->so_rdsel, PSOCK);
1093 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
1095 SOLISTEN_UNLOCK(sol);
1096 wakeup_one(&sol->sol_comp);
1097 if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
1098 pgsigio(&sol->so_sigio, SIGIO, 0);
1102 * Return single connection off a listening socket queue. Main consumer of
1103 * the function is kern_accept4(). Some modules, that do their own accept
1104 * management also use the function. The socket reference held by the
1105 * listen queue is handed to the caller.
1107 * Listening socket must be locked on entry and is returned unlocked on
1109 * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
1112 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
1117 SOLISTEN_LOCK_ASSERT(head);
1119 while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
1120 head->so_error == 0) {
1121 error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH,
1124 SOLISTEN_UNLOCK(head);
1128 if (head->so_error) {
1129 error = head->so_error;
1131 } else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
1132 error = EWOULDBLOCK;
1136 SOLISTEN_UNLOCK(head);
1139 so = TAILQ_FIRST(&head->sol_comp);
1141 KASSERT(so->so_qstate == SQ_COMP,
1142 ("%s: so %p not SQ_COMP", __func__, so));
1144 so->so_qstate = SQ_NONE;
1145 so->so_listen = NULL;
1146 TAILQ_REMOVE(&head->sol_comp, so, so_list);
1147 if (flags & ACCEPT4_INHERIT)
1148 so->so_state |= (head->so_state & SS_NBIO);
1150 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
1152 sorele_locked(head);
1159 * Free socket upon release of the very last reference.
1162 sofree(struct socket *so)
1164 struct protosw *pr = so->so_proto;
1166 SOCK_LOCK_ASSERT(so);
1167 KASSERT(refcount_load(&so->so_count) == 0,
1168 ("%s: so %p has references", __func__, so));
1169 KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE,
1170 ("%s: so %p is on listen queue", __func__, so));
1174 if (so->so_dtor != NULL)
1178 if ((pr->pr_flags & PR_RIGHTS) && !SOLISTENING(so)) {
1179 MPASS(pr->pr_domain->dom_dispose != NULL);
1180 (*pr->pr_domain->dom_dispose)(so);
1182 if (pr->pr_detach != NULL)
1186 * From this point on, we assume that no other references to this
1187 * socket exist anywhere else in the stack. Therefore, no locks need
1188 * to be acquired or held.
1190 if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) {
1191 sbdestroy(so, SO_SND);
1192 sbdestroy(so, SO_RCV);
1194 seldrain(&so->so_rdsel);
1195 seldrain(&so->so_wrsel);
1196 knlist_destroy(&so->so_rdsel.si_note);
1197 knlist_destroy(&so->so_wrsel.si_note);
1202 * Release a reference on a socket while holding the socket lock.
1203 * Unlocks the socket lock before returning.
1206 sorele_locked(struct socket *so)
1208 SOCK_LOCK_ASSERT(so);
1209 if (refcount_release(&so->so_count))
1216 * Close a socket on last file table reference removal. Initiate disconnect
1217 * if connected. Free socket when disconnect complete.
1219 * This function will sorele() the socket. Note that soclose() may be called
1220 * prior to the ref count reaching zero. The actual socket structure will
1221 * not be freed until the ref count reaches zero.
1224 soclose(struct socket *so)
1226 struct accept_queue lqueue;
1228 bool listening, last __diagused;
1230 CURVNET_SET(so->so_vnet);
1231 funsetown(&so->so_sigio);
1232 if (so->so_state & SS_ISCONNECTED) {
1233 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1234 error = sodisconnect(so);
1236 if (error == ENOTCONN)
1242 if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) {
1243 if ((so->so_state & SS_ISDISCONNECTING) &&
1244 (so->so_state & SS_NBIO))
1246 while (so->so_state & SS_ISCONNECTED) {
1247 error = tsleep(&so->so_timeo,
1248 PSOCK | PCATCH, "soclos",
1249 so->so_linger * hz);
1257 if (so->so_proto->pr_close != NULL)
1258 so->so_proto->pr_close(so);
1261 if ((listening = SOLISTENING(so))) {
1264 TAILQ_INIT(&lqueue);
1265 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1266 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1268 so->sol_qlen = so->sol_incqlen = 0;
1270 TAILQ_FOREACH(sp, &lqueue, so_list) {
1272 sp->so_qstate = SQ_NONE;
1273 sp->so_listen = NULL;
1275 last = refcount_release(&so->so_count);
1276 KASSERT(!last, ("%s: released last reference for %p",
1282 struct socket *sp, *tsp;
1284 TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp)
1292 * soabort() is used to abruptly tear down a connection, such as when a
1293 * resource limit is reached (listen queue depth exceeded), or if a listen
1294 * socket is closed while there are sockets waiting to be accepted.
1296 * This interface is tricky, because it is called on an unreferenced socket,
1297 * and must be called only by a thread that has actually removed the socket
1298 * from the listen queue it was on. Likely this thread holds the last
1299 * reference on the socket and soabort() will proceed with sofree(). But
1300 * it might be not the last, as the sockets on the listen queues are seen
1301 * from the protocol side.
1303 * This interface will call into the protocol code, so must not be called
1304 * with any socket locks held. Protocols do call it while holding their own
1305 * recursible protocol mutexes, but this is something that should be subject
1306 * to review in the future.
1308 * Usually socket should have a single reference left, but this is not a
1309 * requirement. In the past, when we have had named references for file
1310 * descriptor and protocol, we asserted that none of them are being held.
1313 soabort(struct socket *so)
1318 if (so->so_proto->pr_abort != NULL)
1319 so->so_proto->pr_abort(so);
1325 soaccept(struct socket *so, struct sockaddr **nam)
1329 CURVNET_SET(so->so_vnet);
1330 error = so->so_proto->pr_accept(so, nam);
1336 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
1339 return (soconnectat(AT_FDCWD, so, nam, td));
1343 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1347 CURVNET_SET(so->so_vnet);
1349 * If protocol is connection-based, can only connect once.
1350 * Otherwise, if connected, try to disconnect first. This allows
1351 * user to disconnect by connecting to, e.g., a null address.
1353 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1354 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1355 (error = sodisconnect(so)))) {
1359 * Prevent accumulated error from previous connection from
1363 if (fd == AT_FDCWD) {
1364 error = so->so_proto->pr_connect(so, nam, td);
1366 error = so->so_proto->pr_connectat(fd, so, nam, td);
1375 soconnect2(struct socket *so1, struct socket *so2)
1379 CURVNET_SET(so1->so_vnet);
1380 error = so1->so_proto->pr_connect2(so1, so2);
1386 sodisconnect(struct socket *so)
1390 if ((so->so_state & SS_ISCONNECTED) == 0)
1392 if (so->so_state & SS_ISDISCONNECTING)
1395 error = so->so_proto->pr_disconnect(so);
1400 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1401 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1405 int clen = 0, error, dontroute;
1407 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1408 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1409 ("sosend_dgram: !PR_ATOMIC"));
1412 resid = uio->uio_resid;
1414 resid = top->m_pkthdr.len;
1416 * In theory resid should be unsigned. However, space must be
1417 * signed, as it might be less than 0 if we over-committed, and we
1418 * must use a signed comparison of space and resid. On the other
1419 * hand, a negative resid causes us to loop sending 0-length
1420 * segments to the protocol.
1428 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1430 td->td_ru.ru_msgsnd++;
1431 if (control != NULL)
1432 clen = control->m_len;
1434 SOCKBUF_LOCK(&so->so_snd);
1435 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1436 SOCKBUF_UNLOCK(&so->so_snd);
1441 error = so->so_error;
1443 SOCKBUF_UNLOCK(&so->so_snd);
1446 if ((so->so_state & SS_ISCONNECTED) == 0) {
1448 * `sendto' and `sendmsg' is allowed on a connection-based
1449 * socket if it supports implied connect. Return ENOTCONN if
1450 * not connected and no address is supplied.
1452 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1453 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1454 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1455 !(resid == 0 && clen != 0)) {
1456 SOCKBUF_UNLOCK(&so->so_snd);
1460 } else if (addr == NULL) {
1461 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1464 error = EDESTADDRREQ;
1465 SOCKBUF_UNLOCK(&so->so_snd);
1471 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1472 * problem and need fixing.
1474 space = sbspace(&so->so_snd);
1475 if (flags & MSG_OOB)
1478 SOCKBUF_UNLOCK(&so->so_snd);
1479 if (resid > space) {
1485 if (flags & MSG_EOR)
1486 top->m_flags |= M_EOR;
1489 * Copy the data from userland into a mbuf chain.
1490 * If no data is to be copied in, a single empty mbuf
1493 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1494 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1496 error = EFAULT; /* only possible error */
1499 space -= resid - uio->uio_resid;
1500 resid = uio->uio_resid;
1502 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1504 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1509 so->so_options |= SO_DONTROUTE;
1513 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1514 * of date. We could have received a reset packet in an interrupt or
1515 * maybe we slept while doing page faults in uiomove() etc. We could
1516 * probably recheck again inside the locking protection here, but
1517 * there are probably other places that this also happens. We must
1521 error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB :
1523 * If the user set MSG_EOF, the protocol understands this flag and
1524 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1526 ((flags & MSG_EOF) &&
1527 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1530 /* If there is more to send set PRUS_MORETOCOME */
1531 (flags & MSG_MORETOCOME) ||
1532 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1533 top, addr, control, td);
1536 so->so_options &= ~SO_DONTROUTE;
1545 if (control != NULL)
1551 * Send on a socket. If send must go all at once and message is larger than
1552 * send buffering, then hard error. Lock against other senders. If must go
1553 * all at once and not enough room now, then inform user that this would
1554 * block and do nothing. Otherwise, if nonblocking, send as much as
1555 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1556 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1557 * in mbuf chain must be small enough to send all at once.
1559 * Returns nonzero on error, timeout or signal; callers must check for short
1560 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1564 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1565 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1569 int clen = 0, error, dontroute;
1570 int atomic = sosendallatonce(so) || top;
1573 struct ktls_session *tls;
1574 int tls_enq_cnt, tls_send_flag;
1578 tls_rtype = TLS_RLTYPE_APP;
1581 resid = uio->uio_resid;
1582 else if ((top->m_flags & M_PKTHDR) != 0)
1583 resid = top->m_pkthdr.len;
1585 resid = m_length(top, NULL);
1587 * In theory resid should be unsigned. However, space must be
1588 * signed, as it might be less than 0 if we over-committed, and we
1589 * must use a signed comparison of space and resid. On the other
1590 * hand, a negative resid causes us to loop sending 0-length
1591 * segments to the protocol.
1593 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1594 * type sockets since that's an error.
1596 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1602 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1603 (so->so_proto->pr_flags & PR_ATOMIC);
1605 td->td_ru.ru_msgsnd++;
1606 if (control != NULL)
1607 clen = control->m_len;
1609 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1615 tls = ktls_hold(so->so_snd.sb_tls_info);
1617 if (tls->mode == TCP_TLS_MODE_SW)
1618 tls_send_flag = PRUS_NOTREADY;
1620 if (control != NULL) {
1621 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1623 if (clen >= sizeof(*cm) &&
1624 cm->cmsg_type == TLS_SET_RECORD_TYPE) {
1625 tls_rtype = *((uint8_t *)CMSG_DATA(cm));
1633 if (resid == 0 && !ktls_permit_empty_frames(tls)) {
1642 SOCKBUF_LOCK(&so->so_snd);
1643 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1644 SOCKBUF_UNLOCK(&so->so_snd);
1649 error = so->so_error;
1651 SOCKBUF_UNLOCK(&so->so_snd);
1654 if ((so->so_state & SS_ISCONNECTED) == 0) {
1656 * `sendto' and `sendmsg' is allowed on a connection-
1657 * based socket if it supports implied connect.
1658 * Return ENOTCONN if not connected and no address is
1661 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1662 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1663 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1664 !(resid == 0 && clen != 0)) {
1665 SOCKBUF_UNLOCK(&so->so_snd);
1669 } else if (addr == NULL) {
1670 SOCKBUF_UNLOCK(&so->so_snd);
1671 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1674 error = EDESTADDRREQ;
1678 space = sbspace(&so->so_snd);
1679 if (flags & MSG_OOB)
1681 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1682 clen > so->so_snd.sb_hiwat) {
1683 SOCKBUF_UNLOCK(&so->so_snd);
1687 if (space < resid + clen &&
1688 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1689 if ((so->so_state & SS_NBIO) ||
1690 (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
1691 SOCKBUF_UNLOCK(&so->so_snd);
1692 error = EWOULDBLOCK;
1695 error = sbwait(so, SO_SND);
1696 SOCKBUF_UNLOCK(&so->so_snd);
1701 SOCKBUF_UNLOCK(&so->so_snd);
1706 if (flags & MSG_EOR)
1707 top->m_flags |= M_EOR;
1710 ktls_frame(top, tls, &tls_enq_cnt,
1712 tls_rtype = TLS_RLTYPE_APP;
1717 * Copy the data from userland into a mbuf
1718 * chain. If resid is 0, which can happen
1719 * only if we have control to send, then
1720 * a single empty mbuf is returned. This
1721 * is a workaround to prevent protocol send
1726 top = m_uiotombuf(uio, M_WAITOK, space,
1727 tls->params.max_frame_len,
1729 ((flags & MSG_EOR) ? M_EOR : 0));
1731 ktls_frame(top, tls,
1732 &tls_enq_cnt, tls_rtype);
1734 tls_rtype = TLS_RLTYPE_APP;
1737 top = m_uiotombuf(uio, M_WAITOK, space,
1738 (atomic ? max_hdr : 0),
1739 (atomic ? M_PKTHDR : 0) |
1740 ((flags & MSG_EOR) ? M_EOR : 0));
1742 error = EFAULT; /* only possible error */
1745 space -= resid - uio->uio_resid;
1746 resid = uio->uio_resid;
1750 so->so_options |= SO_DONTROUTE;
1754 * XXX all the SBS_CANTSENDMORE checks previously
1755 * done could be out of date. We could have received
1756 * a reset packet in an interrupt or maybe we slept
1757 * while doing page faults in uiomove() etc. We
1758 * could probably recheck again inside the locking
1759 * protection here, but there are probably other
1760 * places that this also happens. We must rethink
1765 pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB :
1767 * If the user set MSG_EOF, the protocol understands
1768 * this flag and nothing left to send then use
1769 * PRU_SEND_EOF instead of PRU_SEND.
1771 ((flags & MSG_EOF) &&
1772 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1775 /* If there is more to send set PRUS_MORETOCOME. */
1776 (flags & MSG_MORETOCOME) ||
1777 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
1780 pr_send_flag |= tls_send_flag;
1783 error = so->so_proto->pr_send(so, pr_send_flag, top,
1788 so->so_options &= ~SO_DONTROUTE;
1793 if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
1799 ktls_enqueue(top, so, tls_enq_cnt);
1808 } while (resid && space > 0);
1812 SOCK_IO_SEND_UNLOCK(so);
1820 if (control != NULL)
1826 * Send to a socket from a kernel thread.
1828 * XXXGL: in almost all cases uio is NULL and the mbuf is supplied.
1829 * Exception is nfs/bootp_subr.c. It is arguable that the VNET context needs
1830 * to be set at all. This function should just boil down to a static inline
1831 * calling the protocol method.
1834 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1835 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1839 CURVNET_SET(so->so_vnet);
1840 error = so->so_proto->pr_sosend(so, addr, uio,
1841 top, control, flags, td);
1847 * send(2), write(2) or aio_write(2) on a socket.
1850 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1851 struct mbuf *control, int flags, struct proc *userproc)
1858 len = uio->uio_resid;
1859 CURVNET_SET(so->so_vnet);
1860 error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags,
1865 * Clear transient errors for stream protocols if they made
1866 * some progress. Make exclusion for aio(4) that would
1867 * schedule a new write in case of EWOULDBLOCK and clear
1868 * error itself. See soaio_process_job().
1870 if (uio->uio_resid != len &&
1871 (so->so_proto->pr_flags & PR_ATOMIC) == 0 &&
1873 (error == ERESTART || error == EINTR ||
1874 error == EWOULDBLOCK))
1876 /* Generation of SIGPIPE can be controlled per socket. */
1877 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 &&
1878 (flags & MSG_NOSIGNAL) == 0) {
1879 if (userproc != NULL) {
1881 PROC_LOCK(userproc);
1882 kern_psignal(userproc, SIGPIPE);
1883 PROC_UNLOCK(userproc);
1885 PROC_LOCK(td->td_proc);
1886 tdsignal(td, SIGPIPE);
1887 PROC_UNLOCK(td->td_proc);
1895 * The part of soreceive() that implements reading non-inline out-of-band
1896 * data from a socket. For more complete comments, see soreceive(), from
1897 * which this code originated.
1899 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1900 * unable to return an mbuf chain to the caller.
1903 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1905 struct protosw *pr = so->so_proto;
1909 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1912 m = m_get(M_WAITOK, MT_DATA);
1913 error = pr->pr_rcvoob(so, m, flags & MSG_PEEK);
1917 error = uiomove(mtod(m, void *),
1918 (int) min(uio->uio_resid, m->m_len), uio);
1920 } while (uio->uio_resid && error == 0 && m);
1928 * Following replacement or removal of the first mbuf on the first mbuf chain
1929 * of a socket buffer, push necessary state changes back into the socket
1930 * buffer so that other consumers see the values consistently. 'nextrecord'
1931 * is the callers locally stored value of the original value of
1932 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1933 * NOTE: 'nextrecord' may be NULL.
1935 static __inline void
1936 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1939 SOCKBUF_LOCK_ASSERT(sb);
1941 * First, update for the new value of nextrecord. If necessary, make
1942 * it the first record.
1944 if (sb->sb_mb != NULL)
1945 sb->sb_mb->m_nextpkt = nextrecord;
1947 sb->sb_mb = nextrecord;
1950 * Now update any dependent socket buffer fields to reflect the new
1951 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1952 * addition of a second clause that takes care of the case where
1953 * sb_mb has been updated, but remains the last record.
1955 if (sb->sb_mb == NULL) {
1956 sb->sb_mbtail = NULL;
1957 sb->sb_lastrecord = NULL;
1958 } else if (sb->sb_mb->m_nextpkt == NULL)
1959 sb->sb_lastrecord = sb->sb_mb;
1963 * Implement receive operations on a socket. We depend on the way that
1964 * records are added to the sockbuf by sbappend. In particular, each record
1965 * (mbufs linked through m_next) must begin with an address if the protocol
1966 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1967 * data, and then zero or more mbufs of data. In order to allow parallelism
1968 * between network receive and copying to user space, as well as avoid
1969 * sleeping with a mutex held, we release the socket buffer mutex during the
1970 * user space copy. Although the sockbuf is locked, new data may still be
1971 * appended, and thus we must maintain consistency of the sockbuf during that
1974 * The caller may receive the data as a single mbuf chain by supplying an
1975 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1976 * the count in uio_resid.
1979 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1980 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1982 struct mbuf *m, **mp;
1983 int flags, error, offset;
1985 struct protosw *pr = so->so_proto;
1986 struct mbuf *nextrecord;
1988 ssize_t orig_resid = uio->uio_resid;
1989 bool report_real_len = false;
1994 if (controlp != NULL)
1996 if (flagsp != NULL) {
1997 report_real_len = *flagsp & MSG_TRUNC;
1998 *flagsp &= ~MSG_TRUNC;
1999 flags = *flagsp &~ MSG_EOR;
2002 if (flags & MSG_OOB)
2003 return (soreceive_rcvoob(so, uio, flags));
2006 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
2007 && uio->uio_resid) {
2012 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2017 SOCKBUF_LOCK(&so->so_rcv);
2018 m = so->so_rcv.sb_mb;
2020 * If we have less data than requested, block awaiting more (subject
2021 * to any timeout) if:
2022 * 1. the current count is less than the low water mark, or
2023 * 2. MSG_DONTWAIT is not set
2025 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
2026 sbavail(&so->so_rcv) < uio->uio_resid) &&
2027 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
2028 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
2029 KASSERT(m != NULL || !sbavail(&so->so_rcv),
2030 ("receive: m == %p sbavail == %u",
2031 m, sbavail(&so->so_rcv)));
2032 if (so->so_error || so->so_rerror) {
2036 error = so->so_error;
2038 error = so->so_rerror;
2039 if ((flags & MSG_PEEK) == 0) {
2045 SOCKBUF_UNLOCK(&so->so_rcv);
2048 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2049 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2053 else if (so->so_rcv.sb_tlsdcc == 0 &&
2054 so->so_rcv.sb_tlscc == 0) {
2058 SOCKBUF_UNLOCK(&so->so_rcv);
2062 for (; m != NULL; m = m->m_next)
2063 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
2064 m = so->so_rcv.sb_mb;
2067 if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED |
2068 SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 &&
2069 (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
2070 SOCKBUF_UNLOCK(&so->so_rcv);
2074 if (uio->uio_resid == 0 && !report_real_len) {
2075 SOCKBUF_UNLOCK(&so->so_rcv);
2078 if ((so->so_state & SS_NBIO) ||
2079 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2080 SOCKBUF_UNLOCK(&so->so_rcv);
2081 error = EWOULDBLOCK;
2084 SBLASTRECORDCHK(&so->so_rcv);
2085 SBLASTMBUFCHK(&so->so_rcv);
2086 error = sbwait(so, SO_RCV);
2087 SOCKBUF_UNLOCK(&so->so_rcv);
2094 * From this point onward, we maintain 'nextrecord' as a cache of the
2095 * pointer to the next record in the socket buffer. We must keep the
2096 * various socket buffer pointers and local stack versions of the
2097 * pointers in sync, pushing out modifications before dropping the
2098 * socket buffer mutex, and re-reading them when picking it up.
2100 * Otherwise, we will race with the network stack appending new data
2101 * or records onto the socket buffer by using inconsistent/stale
2102 * versions of the field, possibly resulting in socket buffer
2105 * By holding the high-level sblock(), we prevent simultaneous
2106 * readers from pulling off the front of the socket buffer.
2108 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2110 uio->uio_td->td_ru.ru_msgrcv++;
2111 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
2112 SBLASTRECORDCHK(&so->so_rcv);
2113 SBLASTMBUFCHK(&so->so_rcv);
2114 nextrecord = m->m_nextpkt;
2115 if (pr->pr_flags & PR_ADDR) {
2116 KASSERT(m->m_type == MT_SONAME,
2117 ("m->m_type == %d", m->m_type));
2120 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2122 if (flags & MSG_PEEK) {
2125 sbfree(&so->so_rcv, m);
2126 so->so_rcv.sb_mb = m_free(m);
2127 m = so->so_rcv.sb_mb;
2128 sockbuf_pushsync(&so->so_rcv, nextrecord);
2133 * Process one or more MT_CONTROL mbufs present before any data mbufs
2134 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
2135 * just copy the data; if !MSG_PEEK, we call into the protocol to
2136 * perform externalization (or freeing if controlp == NULL).
2138 if (m != NULL && m->m_type == MT_CONTROL) {
2139 struct mbuf *cm = NULL, *cmn;
2140 struct mbuf **cme = &cm;
2142 struct cmsghdr *cmsg;
2143 struct tls_get_record tgr;
2146 * For MSG_TLSAPPDATA, check for an alert record.
2147 * If found, return ENXIO without removing
2148 * it from the receive queue. This allows a subsequent
2149 * call without MSG_TLSAPPDATA to receive it.
2150 * Note that, for TLS, there should only be a single
2151 * control mbuf with the TLS_GET_RECORD message in it.
2153 if (flags & MSG_TLSAPPDATA) {
2154 cmsg = mtod(m, struct cmsghdr *);
2155 if (cmsg->cmsg_type == TLS_GET_RECORD &&
2156 cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) {
2157 memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr));
2158 if (__predict_false(tgr.tls_type ==
2159 TLS_RLTYPE_ALERT)) {
2160 SOCKBUF_UNLOCK(&so->so_rcv);
2169 if (flags & MSG_PEEK) {
2170 if (controlp != NULL) {
2171 *controlp = m_copym(m, 0, m->m_len,
2173 controlp = &(*controlp)->m_next;
2177 sbfree(&so->so_rcv, m);
2178 so->so_rcv.sb_mb = m->m_next;
2181 cme = &(*cme)->m_next;
2182 m = so->so_rcv.sb_mb;
2184 } while (m != NULL && m->m_type == MT_CONTROL);
2185 if ((flags & MSG_PEEK) == 0)
2186 sockbuf_pushsync(&so->so_rcv, nextrecord);
2187 while (cm != NULL) {
2190 if (pr->pr_domain->dom_externalize != NULL) {
2191 SOCKBUF_UNLOCK(&so->so_rcv);
2193 error = (*pr->pr_domain->dom_externalize)
2194 (cm, controlp, flags);
2195 SOCKBUF_LOCK(&so->so_rcv);
2196 } else if (controlp != NULL)
2200 if (controlp != NULL) {
2201 while (*controlp != NULL)
2202 controlp = &(*controlp)->m_next;
2207 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
2209 nextrecord = so->so_rcv.sb_mb;
2213 if ((flags & MSG_PEEK) == 0) {
2214 KASSERT(m->m_nextpkt == nextrecord,
2215 ("soreceive: post-control, nextrecord !sync"));
2216 if (nextrecord == NULL) {
2217 KASSERT(so->so_rcv.sb_mb == m,
2218 ("soreceive: post-control, sb_mb!=m"));
2219 KASSERT(so->so_rcv.sb_lastrecord == m,
2220 ("soreceive: post-control, lastrecord!=m"));
2224 if (type == MT_OOBDATA)
2227 if ((flags & MSG_PEEK) == 0) {
2228 KASSERT(so->so_rcv.sb_mb == nextrecord,
2229 ("soreceive: sb_mb != nextrecord"));
2230 if (so->so_rcv.sb_mb == NULL) {
2231 KASSERT(so->so_rcv.sb_lastrecord == NULL,
2232 ("soreceive: sb_lastercord != NULL"));
2236 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2237 SBLASTRECORDCHK(&so->so_rcv);
2238 SBLASTMBUFCHK(&so->so_rcv);
2241 * Now continue to read any data mbufs off of the head of the socket
2242 * buffer until the read request is satisfied. Note that 'type' is
2243 * used to store the type of any mbuf reads that have happened so far
2244 * such that soreceive() can stop reading if the type changes, which
2245 * causes soreceive() to return only one of regular data and inline
2246 * out-of-band data in a single socket receive operation.
2250 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
2253 * If the type of mbuf has changed since the last mbuf
2254 * examined ('type'), end the receive operation.
2256 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2257 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
2258 if (type != m->m_type)
2260 } else if (type == MT_OOBDATA)
2263 KASSERT(m->m_type == MT_DATA,
2264 ("m->m_type == %d", m->m_type));
2265 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
2266 len = uio->uio_resid;
2267 if (so->so_oobmark && len > so->so_oobmark - offset)
2268 len = so->so_oobmark - offset;
2269 if (len > m->m_len - moff)
2270 len = m->m_len - moff;
2272 * If mp is set, just pass back the mbufs. Otherwise copy
2273 * them out via the uio, then free. Sockbuf must be
2274 * consistent here (points to current mbuf, it points to next
2275 * record) when we drop priority; we must note any additions
2276 * to the sockbuf when we block interrupts again.
2279 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2280 SBLASTRECORDCHK(&so->so_rcv);
2281 SBLASTMBUFCHK(&so->so_rcv);
2282 SOCKBUF_UNLOCK(&so->so_rcv);
2283 if ((m->m_flags & M_EXTPG) != 0)
2284 error = m_unmapped_uiomove(m, moff, uio,
2287 error = uiomove(mtod(m, char *) + moff,
2289 SOCKBUF_LOCK(&so->so_rcv);
2292 * The MT_SONAME mbuf has already been removed
2293 * from the record, so it is necessary to
2294 * remove the data mbufs, if any, to preserve
2295 * the invariant in the case of PR_ADDR that
2296 * requires MT_SONAME mbufs at the head of
2299 if (pr->pr_flags & PR_ATOMIC &&
2300 ((flags & MSG_PEEK) == 0))
2301 (void)sbdroprecord_locked(&so->so_rcv);
2302 SOCKBUF_UNLOCK(&so->so_rcv);
2306 uio->uio_resid -= len;
2307 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2308 if (len == m->m_len - moff) {
2309 if (m->m_flags & M_EOR)
2311 if (flags & MSG_PEEK) {
2315 nextrecord = m->m_nextpkt;
2316 sbfree(&so->so_rcv, m);
2318 m->m_nextpkt = NULL;
2321 so->so_rcv.sb_mb = m = m->m_next;
2324 so->so_rcv.sb_mb = m_free(m);
2325 m = so->so_rcv.sb_mb;
2327 sockbuf_pushsync(&so->so_rcv, nextrecord);
2328 SBLASTRECORDCHK(&so->so_rcv);
2329 SBLASTMBUFCHK(&so->so_rcv);
2332 if (flags & MSG_PEEK)
2336 if (flags & MSG_DONTWAIT) {
2337 *mp = m_copym(m, 0, len,
2341 * m_copym() couldn't
2343 * Adjust uio_resid back
2345 * down by len bytes,
2346 * which we didn't end
2347 * up "copying" over).
2349 uio->uio_resid += len;
2353 SOCKBUF_UNLOCK(&so->so_rcv);
2354 *mp = m_copym(m, 0, len,
2356 SOCKBUF_LOCK(&so->so_rcv);
2359 sbcut_locked(&so->so_rcv, len);
2362 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2363 if (so->so_oobmark) {
2364 if ((flags & MSG_PEEK) == 0) {
2365 so->so_oobmark -= len;
2366 if (so->so_oobmark == 0) {
2367 so->so_rcv.sb_state |= SBS_RCVATMARK;
2372 if (offset == so->so_oobmark)
2376 if (flags & MSG_EOR)
2379 * If the MSG_WAITALL flag is set (for non-atomic socket), we
2380 * must not quit until "uio->uio_resid == 0" or an error
2381 * termination. If a signal/timeout occurs, return with a
2382 * short count but without error. Keep sockbuf locked
2383 * against other readers.
2385 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
2386 !sosendallatonce(so) && nextrecord == NULL) {
2387 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2388 if (so->so_error || so->so_rerror ||
2389 so->so_rcv.sb_state & SBS_CANTRCVMORE)
2392 * Notify the protocol that some data has been
2393 * drained before blocking.
2395 if (pr->pr_flags & PR_WANTRCVD) {
2396 SOCKBUF_UNLOCK(&so->so_rcv);
2398 pr->pr_rcvd(so, flags);
2399 SOCKBUF_LOCK(&so->so_rcv);
2401 SBLASTRECORDCHK(&so->so_rcv);
2402 SBLASTMBUFCHK(&so->so_rcv);
2404 * We could receive some data while was notifying
2405 * the protocol. Skip blocking in this case.
2407 if (so->so_rcv.sb_mb == NULL) {
2408 error = sbwait(so, SO_RCV);
2410 SOCKBUF_UNLOCK(&so->so_rcv);
2414 m = so->so_rcv.sb_mb;
2416 nextrecord = m->m_nextpkt;
2420 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2421 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
2422 if (report_real_len)
2423 uio->uio_resid -= m_length(m, NULL) - moff;
2425 if ((flags & MSG_PEEK) == 0)
2426 (void) sbdroprecord_locked(&so->so_rcv);
2428 if ((flags & MSG_PEEK) == 0) {
2431 * First part is an inline SB_EMPTY_FIXUP(). Second
2432 * part makes sure sb_lastrecord is up-to-date if
2433 * there is still data in the socket buffer.
2435 so->so_rcv.sb_mb = nextrecord;
2436 if (so->so_rcv.sb_mb == NULL) {
2437 so->so_rcv.sb_mbtail = NULL;
2438 so->so_rcv.sb_lastrecord = NULL;
2439 } else if (nextrecord->m_nextpkt == NULL)
2440 so->so_rcv.sb_lastrecord = nextrecord;
2442 SBLASTRECORDCHK(&so->so_rcv);
2443 SBLASTMBUFCHK(&so->so_rcv);
2445 * If soreceive() is being done from the socket callback,
2446 * then don't need to generate ACK to peer to update window,
2447 * since ACK will be generated on return to TCP.
2449 if (!(flags & MSG_SOCALLBCK) &&
2450 (pr->pr_flags & PR_WANTRCVD)) {
2451 SOCKBUF_UNLOCK(&so->so_rcv);
2453 pr->pr_rcvd(so, flags);
2454 SOCKBUF_LOCK(&so->so_rcv);
2457 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2458 if (orig_resid == uio->uio_resid && orig_resid &&
2459 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2460 SOCKBUF_UNLOCK(&so->so_rcv);
2463 SOCKBUF_UNLOCK(&so->so_rcv);
2468 SOCK_IO_RECV_UNLOCK(so);
2473 * Optimized version of soreceive() for stream (TCP) sockets.
2476 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2477 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2479 int len = 0, error = 0, flags, oresid;
2481 struct mbuf *m, *n = NULL;
2483 /* We only do stream sockets. */
2484 if (so->so_type != SOCK_STREAM)
2489 flags = *flagsp &~ MSG_EOR;
2492 if (controlp != NULL)
2494 if (flags & MSG_OOB)
2495 return (soreceive_rcvoob(so, uio, flags));
2503 * KTLS store TLS records as records with a control message to
2504 * describe the framing.
2506 * We check once here before acquiring locks to optimize the
2509 if (sb->sb_tls_info != NULL)
2510 return (soreceive_generic(so, psa, uio, mp0, controlp,
2514 /* Prevent other readers from entering the socket. */
2515 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
2521 if (sb->sb_tls_info != NULL) {
2523 SOCK_IO_RECV_UNLOCK(so);
2524 return (soreceive_generic(so, psa, uio, mp0, controlp,
2529 /* Easy one, no space to copyout anything. */
2530 if (uio->uio_resid == 0) {
2534 oresid = uio->uio_resid;
2536 /* We will never ever get anything unless we are or were connected. */
2537 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2543 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2545 /* Abort if socket has reported problems. */
2547 if (sbavail(sb) > 0)
2549 if (oresid > uio->uio_resid)
2551 error = so->so_error;
2552 if (!(flags & MSG_PEEK))
2557 /* Door is closed. Deliver what is left, if any. */
2558 if (sb->sb_state & SBS_CANTRCVMORE) {
2559 if (sbavail(sb) > 0)
2565 /* Socket buffer is empty and we shall not block. */
2566 if (sbavail(sb) == 0 &&
2567 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2572 /* Socket buffer got some data that we shall deliver now. */
2573 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2574 ((so->so_state & SS_NBIO) ||
2575 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2576 sbavail(sb) >= sb->sb_lowat ||
2577 sbavail(sb) >= uio->uio_resid ||
2578 sbavail(sb) >= sb->sb_hiwat) ) {
2582 /* On MSG_WAITALL we must wait until all data or error arrives. */
2583 if ((flags & MSG_WAITALL) &&
2584 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2588 * Wait and block until (more) data comes in.
2589 * NB: Drops the sockbuf lock during wait.
2591 error = sbwait(so, SO_RCV);
2597 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2598 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2599 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2603 uio->uio_td->td_ru.ru_msgrcv++;
2605 /* Fill uio until full or current end of socket buffer is reached. */
2606 len = min(uio->uio_resid, sbavail(sb));
2608 /* Dequeue as many mbufs as possible. */
2609 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2613 m_cat(*mp0, sb->sb_mb);
2615 m != NULL && m->m_len <= len;
2617 KASSERT(!(m->m_flags & M_NOTAVAIL),
2618 ("%s: m %p not available", __func__, m));
2620 uio->uio_resid -= m->m_len;
2626 sb->sb_lastrecord = sb->sb_mb;
2627 if (sb->sb_mb == NULL)
2630 /* Copy the remainder. */
2632 KASSERT(sb->sb_mb != NULL,
2633 ("%s: len > 0 && sb->sb_mb empty", __func__));
2635 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2637 len = 0; /* Don't flush data from sockbuf. */
2639 uio->uio_resid -= len;
2650 /* NB: Must unlock socket buffer as uiomove may sleep. */
2652 error = m_mbuftouio(uio, sb->sb_mb, len);
2657 SBLASTRECORDCHK(sb);
2661 * Remove the delivered data from the socket buffer unless we
2662 * were only peeking.
2664 if (!(flags & MSG_PEEK)) {
2666 sbdrop_locked(sb, len);
2668 /* Notify protocol that we drained some data. */
2669 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2670 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2671 !(flags & MSG_SOCALLBCK))) {
2674 so->so_proto->pr_rcvd(so, flags);
2680 * For MSG_WAITALL we may have to loop again and wait for
2681 * more data to come in.
2683 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2686 SBLASTRECORDCHK(sb);
2689 SOCK_IO_RECV_UNLOCK(so);
2694 * Optimized version of soreceive() for simple datagram cases from userspace.
2695 * Unlike in the stream case, we're able to drop a datagram if copyout()
2696 * fails, and because we handle datagrams atomically, we don't need to use a
2697 * sleep lock to prevent I/O interlacing.
2700 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2701 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2703 struct mbuf *m, *m2;
2706 struct protosw *pr = so->so_proto;
2707 struct mbuf *nextrecord;
2711 if (controlp != NULL)
2714 flags = *flagsp &~ MSG_EOR;
2719 * For any complicated cases, fall back to the full
2720 * soreceive_generic().
2722 if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
2723 return (soreceive_generic(so, psa, uio, mp0, controlp,
2727 * Enforce restrictions on use.
2729 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2730 ("soreceive_dgram: wantrcvd"));
2731 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2732 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2733 ("soreceive_dgram: SBS_RCVATMARK"));
2734 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2735 ("soreceive_dgram: P_CONNREQUIRED"));
2738 * Loop blocking while waiting for a datagram.
2740 SOCKBUF_LOCK(&so->so_rcv);
2741 while ((m = so->so_rcv.sb_mb) == NULL) {
2742 KASSERT(sbavail(&so->so_rcv) == 0,
2743 ("soreceive_dgram: sb_mb NULL but sbavail %u",
2744 sbavail(&so->so_rcv)));
2746 error = so->so_error;
2748 SOCKBUF_UNLOCK(&so->so_rcv);
2751 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2752 uio->uio_resid == 0) {
2753 SOCKBUF_UNLOCK(&so->so_rcv);
2756 if ((so->so_state & SS_NBIO) ||
2757 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2758 SOCKBUF_UNLOCK(&so->so_rcv);
2759 return (EWOULDBLOCK);
2761 SBLASTRECORDCHK(&so->so_rcv);
2762 SBLASTMBUFCHK(&so->so_rcv);
2763 error = sbwait(so, SO_RCV);
2765 SOCKBUF_UNLOCK(&so->so_rcv);
2769 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2772 uio->uio_td->td_ru.ru_msgrcv++;
2773 SBLASTRECORDCHK(&so->so_rcv);
2774 SBLASTMBUFCHK(&so->so_rcv);
2775 nextrecord = m->m_nextpkt;
2776 if (nextrecord == NULL) {
2777 KASSERT(so->so_rcv.sb_lastrecord == m,
2778 ("soreceive_dgram: lastrecord != m"));
2781 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2782 ("soreceive_dgram: m_nextpkt != nextrecord"));
2785 * Pull 'm' and its chain off the front of the packet queue.
2787 so->so_rcv.sb_mb = NULL;
2788 sockbuf_pushsync(&so->so_rcv, nextrecord);
2791 * Walk 'm's chain and free that many bytes from the socket buffer.
2793 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2794 sbfree(&so->so_rcv, m2);
2797 * Do a few last checks before we let go of the lock.
2799 SBLASTRECORDCHK(&so->so_rcv);
2800 SBLASTMBUFCHK(&so->so_rcv);
2801 SOCKBUF_UNLOCK(&so->so_rcv);
2803 if (pr->pr_flags & PR_ADDR) {
2804 KASSERT(m->m_type == MT_SONAME,
2805 ("m->m_type == %d", m->m_type));
2807 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2812 /* XXXRW: Can this happen? */
2817 * Packet to copyout() is now in 'm' and it is disconnected from the
2820 * Process one or more MT_CONTROL mbufs present before any data mbufs
2821 * in the first mbuf chain on the socket buffer. We call into the
2822 * protocol to perform externalization (or freeing if controlp ==
2823 * NULL). In some cases there can be only MT_CONTROL mbufs without
2826 if (m->m_type == MT_CONTROL) {
2827 struct mbuf *cm = NULL, *cmn;
2828 struct mbuf **cme = &cm;
2834 cme = &(*cme)->m_next;
2836 } while (m != NULL && m->m_type == MT_CONTROL);
2837 while (cm != NULL) {
2840 if (pr->pr_domain->dom_externalize != NULL) {
2841 error = (*pr->pr_domain->dom_externalize)
2842 (cm, controlp, flags);
2843 } else if (controlp != NULL)
2847 if (controlp != NULL) {
2848 while (*controlp != NULL)
2849 controlp = &(*controlp)->m_next;
2854 KASSERT(m == NULL || m->m_type == MT_DATA,
2855 ("soreceive_dgram: !data"));
2856 while (m != NULL && uio->uio_resid > 0) {
2857 len = uio->uio_resid;
2860 error = uiomove(mtod(m, char *), (int)len, uio);
2865 if (len == m->m_len)
2882 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2883 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2887 CURVNET_SET(so->so_vnet);
2888 error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
2894 soshutdown(struct socket *so, int how)
2897 int error, soerror_enotconn;
2899 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2902 soerror_enotconn = 0;
2905 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2907 * POSIX mandates us to return ENOTCONN when shutdown(2) is
2908 * invoked on a datagram sockets, however historically we would
2909 * actually tear socket down. This is known to be leveraged by
2910 * some applications to unblock process waiting in recvXXX(2)
2911 * by other process that it shares that socket with. Try to meet
2912 * both backward-compatibility and POSIX requirements by forcing
2913 * ENOTCONN but still asking protocol to perform pru_shutdown().
2915 if (so->so_type != SOCK_DGRAM && !SOLISTENING(so)) {
2919 soerror_enotconn = 1;
2922 if (SOLISTENING(so)) {
2923 if (how != SHUT_WR) {
2924 so->so_error = ECONNABORTED;
2925 solisten_wakeup(so); /* unlocks so */
2933 CURVNET_SET(so->so_vnet);
2935 if (pr->pr_flush != NULL)
2936 pr->pr_flush(so, how);
2939 if (how != SHUT_RD) {
2940 error = pr->pr_shutdown(so);
2941 wakeup(&so->so_timeo);
2943 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2945 wakeup(&so->so_timeo);
2949 return (soerror_enotconn ? ENOTCONN : 0);
2953 sorflush(struct socket *so)
2961 * Dislodge threads currently blocked in receive and wait to acquire
2962 * a lock against other simultaneous readers before clearing the
2963 * socket buffer. Don't let our acquire be interrupted by a signal
2964 * despite any existing socket disposition on interruptable waiting.
2968 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
2970 KASSERT(SOLISTENING(so),
2971 ("%s: soiolock(%p) failed", __func__, so));
2976 if (pr->pr_flags & PR_RIGHTS) {
2977 MPASS(pr->pr_domain->dom_dispose != NULL);
2978 (*pr->pr_domain->dom_dispose)(so);
2980 sbrelease(so, SO_RCV);
2981 SOCK_IO_RECV_UNLOCK(so);
2987 * Wrapper for Socket established helper hook.
2988 * Parameters: socket, context of the hook point, hook id.
2991 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2993 struct socket_hhook_data hhook_data = {
3000 CURVNET_SET(so->so_vnet);
3001 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3004 /* Ugly but needed, since hhooks return void for now */
3005 return (hhook_data.status);
3009 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3010 * additional variant to handle the case where the option value needs to be
3011 * some kind of integer, but not a specific size. In addition to their use
3012 * here, these functions are also called by the protocol-level pr_ctloutput()
3016 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3021 * If the user gives us more than we wanted, we ignore it, but if we
3022 * don't get the minimum length the caller wants, we return EINVAL.
3023 * On success, sopt->sopt_valsize is set to however much we actually
3026 if ((valsize = sopt->sopt_valsize) < minlen)
3029 sopt->sopt_valsize = valsize = len;
3031 if (sopt->sopt_td != NULL)
3032 return (copyin(sopt->sopt_val, buf, valsize));
3034 bcopy(sopt->sopt_val, buf, valsize);
3039 * Kernel version of setsockopt(2).
3041 * XXX: optlen is size_t, not socklen_t
3044 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3047 struct sockopt sopt;
3049 sopt.sopt_level = level;
3050 sopt.sopt_name = optname;
3051 sopt.sopt_dir = SOPT_SET;
3052 sopt.sopt_val = optval;
3053 sopt.sopt_valsize = optlen;
3054 sopt.sopt_td = NULL;
3055 return (sosetopt(so, &sopt));
3059 sosetopt(struct socket *so, struct sockopt *sopt)
3064 sbintime_t val, *valp;
3070 CURVNET_SET(so->so_vnet);
3072 if (sopt->sopt_level != SOL_SOCKET) {
3073 if (so->so_proto->pr_ctloutput != NULL)
3074 error = (*so->so_proto->pr_ctloutput)(so, sopt);
3076 error = ENOPROTOOPT;
3078 switch (sopt->sopt_name) {
3079 case SO_ACCEPTFILTER:
3080 error = accept_filt_setopt(so, sopt);
3086 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3089 if (l.l_linger < 0 ||
3090 l.l_linger > USHRT_MAX ||
3091 l.l_linger > (INT_MAX / hz)) {
3096 so->so_linger = l.l_linger;
3098 so->so_options |= SO_LINGER;
3100 so->so_options &= ~SO_LINGER;
3107 case SO_USELOOPBACK:
3111 case SO_REUSEPORT_LB:
3119 error = sooptcopyin(sopt, &optval, sizeof optval,
3125 so->so_options |= sopt->sopt_name;
3127 so->so_options &= ~sopt->sopt_name;
3132 error = sooptcopyin(sopt, &optval, sizeof optval,
3137 if (optval < 0 || optval >= rt_numfibs) {
3141 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
3142 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
3143 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
3144 so->so_fibnum = optval;
3149 case SO_USER_COOKIE:
3150 error = sooptcopyin(sopt, &val32, sizeof val32,
3154 so->so_user_cookie = val32;
3161 error = so->so_proto->pr_setsbopt(so, sopt);
3168 #ifdef COMPAT_FREEBSD32
3169 if (SV_CURPROC_FLAG(SV_ILP32)) {
3170 struct timeval32 tv32;
3172 error = sooptcopyin(sopt, &tv32, sizeof tv32,
3174 CP(tv32, tv, tv_sec);
3175 CP(tv32, tv, tv_usec);
3178 error = sooptcopyin(sopt, &tv, sizeof tv,
3182 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
3183 tv.tv_usec >= 1000000) {
3187 if (tv.tv_sec > INT32_MAX)
3192 valp = sopt->sopt_name == SO_SNDTIMEO ?
3193 (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
3194 &so->so_snd.sb_timeo) :
3195 (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
3196 &so->so_rcv.sb_timeo);
3203 error = sooptcopyin(sopt, &extmac, sizeof extmac,
3207 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
3215 error = sooptcopyin(sopt, &optval, sizeof optval,
3219 if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3223 so->so_ts_clock = optval;
3226 case SO_MAX_PACING_RATE:
3227 error = sooptcopyin(sopt, &val32, sizeof(val32),
3231 so->so_max_pacing_rate = val32;
3235 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3236 error = hhook_run_socket(so, sopt,
3239 error = ENOPROTOOPT;
3242 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
3243 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
3251 * Helper routine for getsockopt.
3254 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
3262 * Documented get behavior is that we always return a value, possibly
3263 * truncated to fit in the user's buffer. Traditional behavior is
3264 * that we always tell the user precisely how much we copied, rather
3265 * than something useful like the total amount we had available for
3266 * her. Note that this interface is not idempotent; the entire
3267 * answer must be generated ahead of time.
3269 valsize = min(len, sopt->sopt_valsize);
3270 sopt->sopt_valsize = valsize;
3271 if (sopt->sopt_val != NULL) {
3272 if (sopt->sopt_td != NULL)
3273 error = copyout(buf, sopt->sopt_val, valsize);
3275 bcopy(buf, sopt->sopt_val, valsize);
3281 sogetopt(struct socket *so, struct sockopt *sopt)
3290 CURVNET_SET(so->so_vnet);
3292 if (sopt->sopt_level != SOL_SOCKET) {
3293 if (so->so_proto->pr_ctloutput != NULL)
3294 error = (*so->so_proto->pr_ctloutput)(so, sopt);
3296 error = ENOPROTOOPT;
3300 switch (sopt->sopt_name) {
3301 case SO_ACCEPTFILTER:
3302 error = accept_filt_getopt(so, sopt);
3307 l.l_onoff = so->so_options & SO_LINGER;
3308 l.l_linger = so->so_linger;
3310 error = sooptcopyout(sopt, &l, sizeof l);
3313 case SO_USELOOPBACK:
3319 case SO_REUSEPORT_LB:
3329 optval = so->so_options & sopt->sopt_name;
3331 error = sooptcopyout(sopt, &optval, sizeof optval);
3335 optval = so->so_proto->pr_domain->dom_family;
3339 optval = so->so_type;
3343 optval = so->so_proto->pr_protocol;
3349 optval = so->so_error;
3352 optval = so->so_rerror;
3359 optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
3360 so->so_snd.sb_hiwat;
3364 optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
3365 so->so_rcv.sb_hiwat;
3369 optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
3370 so->so_snd.sb_lowat;
3374 optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
3375 so->so_rcv.sb_lowat;
3381 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3382 (SOLISTENING(so) ? so->sol_sbsnd_timeo :
3383 so->so_snd.sb_timeo) :
3384 (SOLISTENING(so) ? so->sol_sbrcv_timeo :
3385 so->so_rcv.sb_timeo));
3387 #ifdef COMPAT_FREEBSD32
3388 if (SV_CURPROC_FLAG(SV_ILP32)) {
3389 struct timeval32 tv32;
3391 CP(tv, tv32, tv_sec);
3392 CP(tv, tv32, tv_usec);
3393 error = sooptcopyout(sopt, &tv32, sizeof tv32);
3396 error = sooptcopyout(sopt, &tv, sizeof tv);
3401 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3405 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3409 error = sooptcopyout(sopt, &extmac, sizeof extmac);
3417 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3421 error = mac_getsockopt_peerlabel(
3422 sopt->sopt_td->td_ucred, so, &extmac);
3425 error = sooptcopyout(sopt, &extmac, sizeof extmac);
3431 case SO_LISTENQLIMIT:
3432 optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3436 optval = SOLISTENING(so) ? so->sol_qlen : 0;
3439 case SO_LISTENINCQLEN:
3440 optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3444 optval = so->so_ts_clock;
3447 case SO_MAX_PACING_RATE:
3448 optval = so->so_max_pacing_rate;
3452 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3453 error = hhook_run_socket(so, sopt,
3456 error = ENOPROTOOPT;
3468 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3470 struct mbuf *m, *m_prev;
3471 int sopt_size = sopt->sopt_valsize;
3473 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3476 if (sopt_size > MLEN) {
3477 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3478 if ((m->m_flags & M_EXT) == 0) {
3482 m->m_len = min(MCLBYTES, sopt_size);
3484 m->m_len = min(MLEN, sopt_size);
3486 sopt_size -= m->m_len;
3491 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3496 if (sopt_size > MLEN) {
3497 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3499 if ((m->m_flags & M_EXT) == 0) {
3504 m->m_len = min(MCLBYTES, sopt_size);
3506 m->m_len = min(MLEN, sopt_size);
3508 sopt_size -= m->m_len;
3516 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3518 struct mbuf *m0 = m;
3520 if (sopt->sopt_val == NULL)
3522 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3523 if (sopt->sopt_td != NULL) {
3526 error = copyin(sopt->sopt_val, mtod(m, char *),
3533 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3534 sopt->sopt_valsize -= m->m_len;
3535 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3538 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3539 panic("ip6_sooptmcopyin");
3544 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3546 struct mbuf *m0 = m;
3549 if (sopt->sopt_val == NULL)
3551 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3552 if (sopt->sopt_td != NULL) {
3555 error = copyout(mtod(m, char *), sopt->sopt_val,
3562 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3563 sopt->sopt_valsize -= m->m_len;
3564 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3565 valsize += m->m_len;
3569 /* enough soopt buffer should be given from user-land */
3573 sopt->sopt_valsize = valsize;
3578 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3579 * out-of-band data, which will then notify socket consumers.
3582 sohasoutofband(struct socket *so)
3585 if (so->so_sigio != NULL)
3586 pgsigio(&so->so_sigio, SIGURG, 0);
3587 selwakeuppri(&so->so_rdsel, PSOCK);
3591 sopoll(struct socket *so, int events, struct ucred *active_cred,
3596 * We do not need to set or assert curvnet as long as everyone uses
3599 return (so->so_proto->pr_sopoll(so, events, active_cred, td));
3603 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3609 if (SOLISTENING(so)) {
3610 if (!(events & (POLLIN | POLLRDNORM)))
3612 else if (!TAILQ_EMPTY(&so->sol_comp))
3613 revents = events & (POLLIN | POLLRDNORM);
3614 else if ((events & POLLINIGNEOF) == 0 && so->so_error)
3615 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
3617 selrecord(td, &so->so_rdsel);
3622 SOCK_SENDBUF_LOCK(so);
3623 SOCK_RECVBUF_LOCK(so);
3624 if (events & (POLLIN | POLLRDNORM))
3625 if (soreadabledata(so))
3626 revents |= events & (POLLIN | POLLRDNORM);
3627 if (events & (POLLOUT | POLLWRNORM))
3628 if (sowriteable(so))
3629 revents |= events & (POLLOUT | POLLWRNORM);
3630 if (events & (POLLPRI | POLLRDBAND))
3631 if (so->so_oobmark ||
3632 (so->so_rcv.sb_state & SBS_RCVATMARK))
3633 revents |= events & (POLLPRI | POLLRDBAND);
3634 if ((events & POLLINIGNEOF) == 0) {
3635 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3636 revents |= events & (POLLIN | POLLRDNORM);
3637 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3641 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3642 revents |= events & POLLRDHUP;
3645 (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
3646 selrecord(td, &so->so_rdsel);
3647 so->so_rcv.sb_flags |= SB_SEL;
3649 if (events & (POLLOUT | POLLWRNORM)) {
3650 selrecord(td, &so->so_wrsel);
3651 so->so_snd.sb_flags |= SB_SEL;
3654 SOCK_RECVBUF_UNLOCK(so);
3655 SOCK_SENDBUF_UNLOCK(so);
3662 soo_kqfilter(struct file *fp, struct knote *kn)
3664 struct socket *so = kn->kn_fp->f_data;
3669 switch (kn->kn_filter) {
3671 kn->kn_fop = &soread_filtops;
3672 knl = &so->so_rdsel.si_note;
3677 kn->kn_fop = &sowrite_filtops;
3678 knl = &so->so_wrsel.si_note;
3683 kn->kn_fop = &soempty_filtops;
3684 knl = &so->so_wrsel.si_note;
3693 if (SOLISTENING(so)) {
3694 knlist_add(knl, kn, 1);
3696 SOCK_BUF_LOCK(so, which);
3697 knlist_add(knl, kn, 1);
3698 sb->sb_flags |= SB_KNOTE;
3699 SOCK_BUF_UNLOCK(so, which);
3706 filt_sordetach(struct knote *kn)
3708 struct socket *so = kn->kn_fp->f_data;
3711 knlist_remove(&so->so_rdsel.si_note, kn, 1);
3712 if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3713 so->so_rcv.sb_flags &= ~SB_KNOTE;
3714 so_rdknl_unlock(so);
3719 filt_soread(struct knote *kn, long hint)
3723 so = kn->kn_fp->f_data;
3725 if (SOLISTENING(so)) {
3726 SOCK_LOCK_ASSERT(so);
3727 kn->kn_data = so->sol_qlen;
3729 kn->kn_flags |= EV_EOF;
3730 kn->kn_fflags = so->so_error;
3733 return (!TAILQ_EMPTY(&so->sol_comp));
3736 SOCK_RECVBUF_LOCK_ASSERT(so);
3738 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3739 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3740 kn->kn_flags |= EV_EOF;
3741 kn->kn_fflags = so->so_error;
3743 } else if (so->so_error || so->so_rerror)
3746 if (kn->kn_sfflags & NOTE_LOWAT) {
3747 if (kn->kn_data >= kn->kn_sdata)
3749 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3752 /* This hook returning non-zero indicates an event, not error */
3753 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3757 filt_sowdetach(struct knote *kn)
3759 struct socket *so = kn->kn_fp->f_data;
3762 knlist_remove(&so->so_wrsel.si_note, kn, 1);
3763 if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3764 so->so_snd.sb_flags &= ~SB_KNOTE;
3765 so_wrknl_unlock(so);
3770 filt_sowrite(struct knote *kn, long hint)
3774 so = kn->kn_fp->f_data;
3776 if (SOLISTENING(so))
3779 SOCK_SENDBUF_LOCK_ASSERT(so);
3780 kn->kn_data = sbspace(&so->so_snd);
3782 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3784 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3785 kn->kn_flags |= EV_EOF;
3786 kn->kn_fflags = so->so_error;
3788 } else if (so->so_error) /* temporary udp error */
3790 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3791 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3793 else if (kn->kn_sfflags & NOTE_LOWAT)
3794 return (kn->kn_data >= kn->kn_sdata);
3796 return (kn->kn_data >= so->so_snd.sb_lowat);
3800 filt_soempty(struct knote *kn, long hint)
3804 so = kn->kn_fp->f_data;
3806 if (SOLISTENING(so))
3809 SOCK_SENDBUF_LOCK_ASSERT(so);
3810 kn->kn_data = sbused(&so->so_snd);
3812 if (kn->kn_data == 0)
3819 socheckuid(struct socket *so, uid_t uid)
3824 if (so->so_cred->cr_uid != uid)
3830 * These functions are used by protocols to notify the socket layer (and its
3831 * consumers) of state changes in the sockets driven by protocol-side events.
3835 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3837 * Normal sequence from the active (originating) side is that
3838 * soisconnecting() is called during processing of connect() call, resulting
3839 * in an eventual call to soisconnected() if/when the connection is
3840 * established. When the connection is torn down soisdisconnecting() is
3841 * called during processing of disconnect() call, and soisdisconnected() is
3842 * called when the connection to the peer is totally severed. The semantics
3843 * of these routines are such that connectionless protocols can call
3844 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3845 * calls when setting up a ``connection'' takes no time.
3847 * From the passive side, a socket is created with two queues of sockets:
3848 * so_incomp for connections in progress and so_comp for connections already
3849 * made and awaiting user acceptance. As a protocol is preparing incoming
3850 * connections, it creates a socket structure queued on so_incomp by calling
3851 * sonewconn(). When the connection is established, soisconnected() is
3852 * called, and transfers the socket structure to so_comp, making it available
3855 * If a socket is closed with sockets on either so_incomp or so_comp, these
3856 * sockets are dropped.
3858 * If higher-level protocols are implemented in the kernel, the wakeups done
3859 * here will sometimes cause software-interrupt process scheduling.
3862 soisconnecting(struct socket *so)
3866 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3867 so->so_state |= SS_ISCONNECTING;
3872 soisconnected(struct socket *so)
3874 bool last __diagused;
3877 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3878 so->so_state |= SS_ISCONNECTED;
3880 if (so->so_qstate == SQ_INCOMP) {
3881 struct socket *head = so->so_listen;
3884 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
3886 * Promoting a socket from incomplete queue to complete, we
3887 * need to go through reverse order of locking. We first do
3888 * trylock, and if that doesn't succeed, we go the hard way
3889 * leaving a reference and rechecking consistency after proper
3892 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3895 SOLISTEN_LOCK(head);
3897 if (__predict_false(head != so->so_listen)) {
3899 * The socket went off the listen queue,
3900 * should be lost race to close(2) of sol.
3901 * The socket is about to soabort().
3904 sorele_locked(head);
3907 last = refcount_release(&head->so_count);
3908 KASSERT(!last, ("%s: released last reference for %p",
3912 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3913 TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3914 head->sol_incqlen--;
3915 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3917 so->so_qstate = SQ_COMP;
3919 solisten_wakeup(head); /* unlocks */
3921 SOCK_RECVBUF_LOCK(so);
3922 soupcall_set(so, SO_RCV,
3923 head->sol_accept_filter->accf_callback,
3924 head->sol_accept_filter_arg);
3925 so->so_options &= ~SO_ACCEPTFILTER;
3926 ret = head->sol_accept_filter->accf_callback(so,
3927 head->sol_accept_filter_arg, M_NOWAIT);
3928 if (ret == SU_ISCONNECTED) {
3929 soupcall_clear(so, SO_RCV);
3930 SOCK_RECVBUF_UNLOCK(so);
3933 SOCK_RECVBUF_UNLOCK(so);
3935 SOLISTEN_UNLOCK(head);
3940 wakeup(&so->so_timeo);
3946 soisdisconnecting(struct socket *so)
3950 so->so_state &= ~SS_ISCONNECTING;
3951 so->so_state |= SS_ISDISCONNECTING;
3953 if (!SOLISTENING(so)) {
3954 SOCK_RECVBUF_LOCK(so);
3955 socantrcvmore_locked(so);
3956 SOCK_SENDBUF_LOCK(so);
3957 socantsendmore_locked(so);
3960 wakeup(&so->so_timeo);
3964 soisdisconnected(struct socket *so)
3970 * There is at least one reader of so_state that does not
3971 * acquire socket lock, namely soreceive_generic(). Ensure
3972 * that it never sees all flags that track connection status
3973 * cleared, by ordering the update with a barrier semantic of
3974 * our release thread fence.
3976 so->so_state |= SS_ISDISCONNECTED;
3977 atomic_thread_fence_rel();
3978 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3980 if (!SOLISTENING(so)) {
3982 SOCK_RECVBUF_LOCK(so);
3983 socantrcvmore_locked(so);
3984 SOCK_SENDBUF_LOCK(so);
3985 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3986 socantsendmore_locked(so);
3989 wakeup(&so->so_timeo);
3993 soiolock(struct socket *so, struct sx *sx, int flags)
3997 KASSERT((flags & SBL_VALID) == flags,
3998 ("soiolock: invalid flags %#x", flags));
4000 if ((flags & SBL_WAIT) != 0) {
4001 if ((flags & SBL_NOINTR) != 0) {
4004 error = sx_xlock_sig(sx);
4008 } else if (!sx_try_xlock(sx)) {
4009 return (EWOULDBLOCK);
4012 if (__predict_false(SOLISTENING(so))) {
4020 soiounlock(struct sx *sx)
4026 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4029 sodupsockaddr(const struct sockaddr *sa, int mflags)
4031 struct sockaddr *sa2;
4033 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4035 bcopy(sa, sa2, sa->sa_len);
4040 * Register per-socket destructor.
4043 sodtor_set(struct socket *so, so_dtor_t *func)
4046 SOCK_LOCK_ASSERT(so);
4051 * Register per-socket buffer upcalls.
4054 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4058 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4068 SOCK_BUF_LOCK_ASSERT(so, which);
4069 sb->sb_upcall = func;
4070 sb->sb_upcallarg = arg;
4071 sb->sb_flags |= SB_UPCALL;
4075 soupcall_clear(struct socket *so, sb_which which)
4079 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4089 SOCK_BUF_LOCK_ASSERT(so, which);
4090 KASSERT(sb->sb_upcall != NULL,
4091 ("%s: so %p no upcall to clear", __func__, so));
4092 sb->sb_upcall = NULL;
4093 sb->sb_upcallarg = NULL;
4094 sb->sb_flags &= ~SB_UPCALL;
4098 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
4101 SOLISTEN_LOCK_ASSERT(so);
4102 so->sol_upcall = func;
4103 so->sol_upcallarg = arg;
4107 so_rdknl_lock(void *arg)
4109 struct socket *so = arg;
4112 if (SOLISTENING(so)) {
4115 SOCK_RECVBUF_LOCK(so);
4116 if (__predict_false(SOLISTENING(so))) {
4117 SOCK_RECVBUF_UNLOCK(so);
4124 so_rdknl_unlock(void *arg)
4126 struct socket *so = arg;
4128 if (SOLISTENING(so))
4129 SOLISTEN_UNLOCK(so);
4131 SOCK_RECVBUF_UNLOCK(so);
4135 so_rdknl_assert_lock(void *arg, int what)
4137 struct socket *so = arg;
4139 if (what == LA_LOCKED) {
4140 if (SOLISTENING(so))
4141 SOLISTEN_LOCK_ASSERT(so);
4143 SOCK_RECVBUF_LOCK_ASSERT(so);
4145 if (SOLISTENING(so))
4146 SOLISTEN_UNLOCK_ASSERT(so);
4148 SOCK_RECVBUF_UNLOCK_ASSERT(so);
4153 so_wrknl_lock(void *arg)
4155 struct socket *so = arg;
4158 if (SOLISTENING(so)) {
4161 SOCK_SENDBUF_LOCK(so);
4162 if (__predict_false(SOLISTENING(so))) {
4163 SOCK_SENDBUF_UNLOCK(so);
4170 so_wrknl_unlock(void *arg)
4172 struct socket *so = arg;
4174 if (SOLISTENING(so))
4175 SOLISTEN_UNLOCK(so);
4177 SOCK_SENDBUF_UNLOCK(so);
4181 so_wrknl_assert_lock(void *arg, int what)
4183 struct socket *so = arg;
4185 if (what == LA_LOCKED) {
4186 if (SOLISTENING(so))
4187 SOLISTEN_LOCK_ASSERT(so);
4189 SOCK_SENDBUF_LOCK_ASSERT(so);
4191 if (SOLISTENING(so))
4192 SOLISTEN_UNLOCK_ASSERT(so);
4194 SOCK_SENDBUF_UNLOCK_ASSERT(so);
4199 * Create an external-format (``xsocket'') structure using the information in
4200 * the kernel-format socket structure pointed to by so. This is done to
4201 * reduce the spew of irrelevant information over this interface, to isolate
4202 * user code from changes in the kernel structure, and potentially to provide
4203 * information-hiding if we decide that some of this information should be
4204 * hidden from users.
4207 sotoxsocket(struct socket *so, struct xsocket *xso)
4210 bzero(xso, sizeof(*xso));
4211 xso->xso_len = sizeof *xso;
4212 xso->xso_so = (uintptr_t)so;
4213 xso->so_type = so->so_type;
4214 xso->so_options = so->so_options;
4215 xso->so_linger = so->so_linger;
4216 xso->so_state = so->so_state;
4217 xso->so_pcb = (uintptr_t)so->so_pcb;
4218 xso->xso_protocol = so->so_proto->pr_protocol;
4219 xso->xso_family = so->so_proto->pr_domain->dom_family;
4220 xso->so_timeo = so->so_timeo;
4221 xso->so_error = so->so_error;
4222 xso->so_uid = so->so_cred->cr_uid;
4223 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
4224 if (SOLISTENING(so)) {
4225 xso->so_qlen = so->sol_qlen;
4226 xso->so_incqlen = so->sol_incqlen;
4227 xso->so_qlimit = so->sol_qlimit;
4228 xso->so_oobmark = 0;
4230 xso->so_state |= so->so_qstate;
4231 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
4232 xso->so_oobmark = so->so_oobmark;
4233 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
4234 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
4239 so_sockbuf_rcv(struct socket *so)
4242 return (&so->so_rcv);
4246 so_sockbuf_snd(struct socket *so)
4249 return (&so->so_snd);
4253 so_state_get(const struct socket *so)
4256 return (so->so_state);
4260 so_state_set(struct socket *so, int val)
4267 so_options_get(const struct socket *so)
4270 return (so->so_options);
4274 so_options_set(struct socket *so, int val)
4277 so->so_options = val;
4281 so_error_get(const struct socket *so)
4284 return (so->so_error);
4288 so_error_set(struct socket *so, int val)
4295 so_linger_get(const struct socket *so)
4298 return (so->so_linger);
4302 so_linger_set(struct socket *so, int val)
4305 KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz),
4306 ("%s: val %d out of range", __func__, val));
4308 so->so_linger = val;
4312 so_protosw_get(const struct socket *so)
4315 return (so->so_proto);
4319 so_protosw_set(struct socket *so, struct protosw *val)
4326 so_sorwakeup(struct socket *so)
4333 so_sowwakeup(struct socket *so)
4340 so_sorwakeup_locked(struct socket *so)
4343 sorwakeup_locked(so);
4347 so_sowwakeup_locked(struct socket *so)
4350 sowwakeup_locked(so);
4354 so_lock(struct socket *so)
4361 so_unlock(struct socket *so)